<template>
	<view class="appeal-page">
		<view class="upload-box" v-if="commissionReceipt == 2">
			<view class="uni-title">上传评价截图凭证:</view>
			<view class="uni-tip" style="color: red;font-weight: bold">至少上传一张图片</view>
			<view class="upload-img" ref="one" @click="chooseImage('one')">
				<view class="img-upload">
					<view class="img-add" v-if="imgUrl.one == ''">
						<view class="upload-icon el-icon-ali-upload-img"></view>
					</view>
				</view>
			</view>
			<view class="upload-img" ref="two" @click="chooseImage('two')" v-if="imgUrl.one">
				<view class="img-upload">
					<view class="img-add" v-if="imgUrl.two == ''">
						<view class="upload-icon el-icon-ali-upload-img"></view>
				    </view>
				</view>
			</view>
			<view class="upload-img" ref="three" @click="chooseImage('three')" v-if="imgUrl.two">
				<view class="img-upload">
					<view class="img-add" v-if="imgUrl.three == ''">
						<view class="upload-icon el-icon-ali-upload-img"></view>
					</view>
				</view>
			</view>
		</view>

		<view class="show-img-box" v-else>
			<view v-if="imgArr.length != 0">
				<view class="uni-title" style="color: #4b95ff;">已上传截图:</view>
				<image class="img" v-for="(item,index) in imgArr" :key="index" :src="item" mode=""/>
			</view>
		</view>

		<button v-if="commissionReceipt==2" :loading="loading" :disabled="loading" class="submit-btn" @click="exchangeCommission">兑换</button>

    </view>
</template>

<script>
	import qiniuUploader from '../../components/qiniu/qiniuUploader.js';
    import {
        apiGetAppealInfo,
        apiCreatePushAppeal,
        apiUploadToken, apiExchangeCommission
    } from '../../../http/apis.js'
	import {
		mapState
	} from 'vuex'
	export default {
        computed: {
            ...mapState(['token'])
        },
        data() {
            return {
                appealForm:{
                    token: '',
                    task_type: '',
                    task_code: '',
                    type: 2,
                    assess_img_url:'',
                    order_num: '',
                    tb_name: '',
                    merchant_id: ''
                },
                imgUrl: {
                    one: '',
                    two: '',
                    three: ''
                },
                uploadToken: '',
                commissionReceipt: 2,// 是否展示提交
                imgArr: [],
                appealResultImgUrls: [],
                appealData: [],
                reappeal_why: '',// 重新申述的描述
                appealTaskId: '',
                tabType: 1,
                loading: false
            };
        },
        onLoad(options) {
            this.commissionReceipt = options.commission_receipt
            this.appealForm.task_code = options.taskCode
            this.appealForm.order_num = options.orderNum
            this.tabType = options.tabType
            this.appealForm.merchant_id = options.merchant_id

            this.appealForm.token = this.token
            apiUploadToken({}).then(res =>{
                if(res.data.code == 1)  {
                    this.uploadToken = res.data.msg
                }
            }).catch(res => {
                this.$msg.showToast(res.data.msg)
            })

            if(this.commissionReceipt != 2){
                apiGetAppealInfo({
                    token: this.appealForm.token,
                    task_type: this.appealForm.task_type,
                    type: 2,
                    task_code: this.appealForm.task_code
                }).then(res =>{
                    if(res.data.code == 1)  {
                        if(res.data.msg.assess_img_url){
                            this.imgArr =  res.data.msg.assess_img_url.split(',')
                            if (res.data.msg.appeal_result_img_url) {
                                this.appealResultImgUrls =  res.data.msg.appeal_result_img_url.split(',')
                            }
                            this.appealTaskId = res.data.msg.id
                            this.appealData =  res.data.msg.appeal_why_result
                        }
                    }
                }).catch(res => {
                    this.$msg.showToast(res.data.msg)
                })
            }
        },
        onShow() {},
        onHide() {},
        mounted() {},
        methods: {
            chooseImage(type) {
                var that = this
                uni.chooseImage({
                    count: 1,
                    sizeType: ['origial'],
                    success: res => {
                        var uploads = ''
                        if(type == 'one'){
                            uploads = that.$refs.one.$el;
                        } else if(type == 'two') {
                            uploads = that.$refs.two.$el;
                        } else {
                            uploads = that.$refs.three.$el;
                        }
                        const uploadBox = uploads.querySelector('.img-upload');
                        uploadBox.style.backgroundImage = `url('${res.tempFilePaths[0]}')`;
                        uploadBox.className = 'img-upload';
                        // that.files[type].filePath = res.tempFilePaths[0];
                        that.uploadImgTool(res,res.tempFiles[0].size > 1570000,type);
                    },
                    fail: function() {
                        that.$msg.showToast('载入图片失败，请稍后再试')
                    }
                });
            },

            uploadImgTool(typeimg,fileSize,type){
                var that = this;
                uni.showLoading({
                    title: '上传中',
                    mask: true
                })
                uni.getImageInfo({
                    src:typeimg.tempFilePaths[0],
                    success(res) {
                        let canvasWidth = res.width //图片原始长宽
                        let canvasHeight = res.height
                        let img = new Image()
                        img.src = res.path
                        let canvas = document.createElement('canvas');
                        let ctx = canvas.getContext('2d')
                        let scale = res.height/res.width
                        canvas.width = fileSize == true ? 500 : canvasWidth
                        canvas.height = fileSize == true ? 500*scale : canvasHeight
                        ctx.drawImage(img, 0, 0, fileSize == true ? 500 : canvasWidth , fileSize == true ? 500*scale : canvasHeight )//fileSize == true ? 300 : canvasHeight / 2

                        canvas.toBlob(function(fileSrc) {
                            let imgSrc = window.URL.createObjectURL(fileSrc)
                            var random = Math.floor(Math.random() * (1000 - 1)) + 1
                            var timestamp=new Date().getTime();
                            var name=imgSrc.substring(imgSrc.lastIndexOf("-")+1);
                            var key = name + random.toString() + timestamp.toString() + '.png'
                             qiniuUploader.upload(
                                imgSrc,
                                res => {
                                    //图片上传完成后返回值
                                    that.imgUrl[type] = res.imageURL;
                                    that.$msg.showToast('上传成功')
                                },
                                error => {
                                    // resolve(error)
                                    uni.hideLoading()
                                    that.$msg.showToast('上传失败')
                                },
                                {
                                    region: that.GLOBAL.REGION_VALUE, // （必须填写正确）ECN, SCN, NCN, NA, ASG，分别对应七牛的：华东，华南，华北，北美，新加坡 5 个区域
                                    domain: that.GLOBAL.QINIU_URL, // // bucket 域名，下载资源时用到。如果设置，会在 success callback 的 res 参数加上可以直接使用的 ImageURL                                         字  段。否则需要自己拼接
                                    key: 'commissionReceipt/' + key, // [非必须]自定义文件 key。如果不设置，默认为使用微信小程序 API 的临时文件名
                                    // 以下方法三选一即可，优先级为：uptoken > uptokenURL > uptokenFunc
                                    uptoken: that.uploadToken // 由其他程序生成七牛 uptoken
                                },
                                res => {
                                     //上传进度
                                    if(res.progress === 100){
                                        uni.hideLoading()
                                    }
                                }
                            );
                        })
                    }
                })

            },

            exchangeCommission(){
                var imgUrlString = ''
                Object.values(this.imgUrl).forEach((item, index) => {
                    if(item){
                        imgUrlString += item + ','
                    }
                })
                if(!imgUrlString){
                    uni.showToast({title:'请先上传图片',duration: 1000,icon:'none'})
                    return
                }
                this.appealForm.assess_img_url = imgUrlString.substring(0,imgUrlString.length-1)
                uni.showLoading({
                    title: '提交中...',
                    mask: true
                })
                this.loading = true
                apiExchangeCommission(this.appealForm).then(res =>{
                    uni.hideLoading()
                    if(res.data.code == 1)  {
                        this.$msg.showToast(res.data.msg)
                        setTimeout(()=>{
                            this.loading = false
                            uni.switchTab({
                                url: './taskList'
                            });
                        },1000)
                    } else {
                        this.loading = false
                        this.$msg.showToast(res.data.msg)
                    }
                }).catch(res => {
                    uni.hideLoading()
                    this.loading = false
                    this.$msg.showToast(res.data.msg)
                })
            }
        }

	};
</script>

<style lang="scss">
	page {
		background: #FFFFFF;
		padding: 0 20upx;

	}
	.appeal-page {
		overflow-y: scroll;
		overflow-x: hidden;
		margin-bottom: 150upx;
		.uni-title {
			font-size: 56upx;
			margin-bottom: 10upx;
		}
		.upload-box {
			margin-top: 40upx;
            box-shadow: 0px 0px 10upx 0px rgba(0, 0, 0, 0.3);
            border-radius: 20upx;
			.upload-img {
				display: inline-block;
				margin-right: 20upx;
				margin-bottom: 20upx;
				vertical-align: middle;
			}
			.img-upload {
				// width: 100px;
				// height: 100px;
				border: 0.5px dotted gray;
				position: relative;
				width: 210upx;
				height: 320upx;
				box-sizing: border-box;
				background-size: cover;
				background-repeat: no-repeat;
				background-position: center;
				border-radius: 10upx;
				.img-add {
					font-size: 60upx;
					line-height: 320upx;
					text-align: center;
					.upload-icon {
						font-size: 50upx;
						color: #666666;
					}
				}
			}
		}

		.show-img-box {
			margin-top: 30upx;
			.img {
				width: 210upx;
				height: 320upx;
				border: 1px solid #e0e0e0;
				margin-right: 20upx;
				margin-bottom: 20upx;
			}
		}
		.submit-btn {
			position: fixed;
			bottom: 32upx;
			left: 32upx;
			right: 32upx;
			font-size: 18px;
			color: #fff;
			text-align: center;
			line-height: 50px;
			background: $theme-background-color;
		}
	}
</style>
